var battle = require('./battle');
var item = require('./item');
var experience = require('./experience');
var playerId;
var connection;
var socket;
var clientInfo;

function handleProtocol(conn, soc, client) {
    connection = conn;
    exports.connection = connection;
    socket = soc;
    exports.socket = socket;
    clientInfo = client;
    exports.clientInfo = clientInfo;

    switch (clientInfo.protocol) {
        case 10000://返回玩家信息
            pro10000(connection, socket, clientInfo);
            break;
        case 10001://创建角色
            pro10001(connection, socket, clientInfo);
            break;
        case 10002://玩家登录
            pro10002(connection, socket, clientInfo);
            break;
        case 10003://战斗
            pro10003(connection, socket, clientInfo);
            break;
        case 10004://更改属性点
            pro10004(connection, socket, clientInfo);
            break;
        case 10005://获取物品列表
            pro10005(connection, socket, clientInfo);
            break;
        case 10006://添加物品到背包
            pro10006(connection, socket, clientInfo);
            break;
        case 10007://技能安装
            pro10007(connection, socket, clientInfo);
            break;
        case 10008://外观安装
            pro10008(connection, socket, clientInfo);
            break;
        case 10009://外观列表
            pro10009(connection, socket, clientInfo);
            break;
        case 10010://技能列表
            pro10010(connection, socket, clientInfo);
            break;
        case 10011://获取挂机经验
            pro10011(connection, socket, clientInfo);
            break;
        case 10012://使用或丢弃物品
            pro10012(connection, socket, clientInfo);
            break;
        case 10013://请求pve
            pro10013();
            break;
    }
}

exports.handleProtocol = handleProtocol;

function pro10000(connection, socket, clientInfo) {
    var select = 'select * from player where playerid="' + clientInfo.data.playerid + '" limit 1';
    connection.query(select, function (err, rows) {
        if (err) {
            console.log('select err 10000' + err);
            return;
        }
        var protocolInfo = {protocol: clientInfo.protocol, data: rows[0]};
        playerId = rows[0].playerid;
        exports.playerId = playerId;
        sendData(socket, protocolInfo);
    });
}
function pro10001(connection, socket, clientInfo) {
    var playerpoint = 5 - clientInfo.data.playerpower - clientInfo.data.playerintelligence - clientInfo.data.playernc - clientInfo.data.playergay;
    var isOkNum = 0;
    var insert = 'insert into player(playerid,playername,playerlv,playerexperience,playerbyte,playerhealth,playerpower,playerintelligence,playernc,playergay,playerpoint,hangexp) ' + 'values("' + clientInfo.data.playerid + '","' + clientInfo.data.playername + '",1,0,0,0,' + clientInfo.data.playerpower + ',' + clientInfo.data.playerintelligence + ',' + clientInfo.data.playernc + ',' + clientInfo.data.playergay + ',' + playerpoint + ',0)';
    var insert2 = 'insert into backpack(id) values("' + clientInfo.data.playerid + '")';
    var insert3 = 'insert into skill(id) values("' + clientInfo.data.playerid + '")';
    var insert4 = 'insert into appearance(id) values("' + clientInfo.data.playerid + '")';
    connection.query(insert, function (err, res) {
        if (err) {
            if (err.code == 'ER_DUP_ENTRY') {
                console.log('insert err 10001' + err);
                var protocolInfo = {protocol: clientInfo.protocol, data: {result: 2, msg: '角色名已存在'}};
                sendData(socket, protocolInfo);
                return;
            }
            else {
                console.log('insert err 10001' + err);
                var protocolInfo = {protocol: clientInfo.protocol, data: {result: 0, msg: '创建失败'}};
                sendData(socket, protocolInfo);
                return;
            }
        }
        isOkNum++;
        if (isOkNum >= 4)
            isOk();
    });
    connection.query(insert2, function (err, res) {
        if (err) {
            if (err.code == 'ER_DUP_ENTRY') {
                console.log('insert err 10001' + err);
                var protocolInfo = {protocol: clientInfo.protocol, data: {result: 2, msg: '角色名已存在'}};
                sendData(socket, protocolInfo);
                return;
            }
            else {
                console.log('insert err 10001' + err);
                var protocolInfo = {protocol: clientInfo.protocol, data: {result: 0, msg: '创建失败'}};
                sendData(socket, protocolInfo);
                return;
            }
        }
        isOkNum++;
        if (isOkNum >= 4)
            isOk();
    });
    connection.query(insert3, function (err, res) {
        if (err) {
            if (err.code == 'ER_DUP_ENTRY') {
                console.log('insert err 10001' + err);
                var protocolInfo = {protocol: clientInfo.protocol, data: {result: 2, msg: '角色名已存在'}};
                sendData(socket, protocolInfo);
                return;
            }
            else {
                console.log('insert err 10001' + err);
                var protocolInfo = {protocol: clientInfo.protocol, data: {result: 0, msg: '创建失败'}};
                sendData(socket, protocolInfo);
                return;
            }
        }
        isOkNum++;
        if (isOkNum >= 4)
            isOk();
    });
    connection.query(insert4, function (err, res) {
        if (err) {
            if (err.code == 'ER_DUP_ENTRY') {
                console.log('insert err 10001' + err);
                var protocolInfo = {protocol: clientInfo.protocol, data: {result: 2, msg: '角色名已存在'}};
                sendData(socket, protocolInfo);
                return;
            }
            else {
                console.log('insert err 10001' + err);
                var protocolInfo = {protocol: clientInfo.protocol, data: {result: 0, msg: '创建失败'}};
                sendData(socket, protocolInfo);
                return;
            }
        }
        isOkNum++;
        if (isOkNum >= 4)
            isOk();
    });
    function isOk() {
        var protocolInfo = {protocol: clientInfo.protocol, data: {result: 1, msg: '创建成功'}};
        sendData(socket, protocolInfo);
    }
}
function pro10002(connection, socket, clientInfo) {
    var select = 'select playername from player where playerid="' + clientInfo.data.playerid + '" limit 1';
    connection.query(select, function (err, rows) {
        if (err) {
            console.log('select err 10002' + err);
            var protocolInfo = {protocol: clientInfo.protocol, data: {result: 0, msg: '登录失败'}};
        }
        else if (rows.length == 0)
            var protocolInfo = {
                protocol: clientInfo.protocol,
                data: {result: 2, msg: '需要创建', playerpoint: 5}
            };
        else
            var protocolInfo = {protocol: clientInfo.protocol, data: {result: 1, msg: '可以登录'}};
        sendData(socket, protocolInfo);
    });
}

function pro10003(connection, socket, clientInfo) {
    var select = 'select * from player where playerid="' + clientInfo.data.playerid1 + '" limit 1';
    var select2 = 'select * from player where playerid="' + clientInfo.data.playerid2 + '" limit 1';
    var player1;
    var player2;
    connection.query(select, function (err, rows) {
        if (err) {
            console.log('insert err 10003' + err);
            notReady();
        }
        if (rows.length == 0)
            notReady();
        else {
            player1 = rows[0];
            if (player2 != null)
                allReady()
        }
    });
    connection.query(select2, function (err, rows) {
        if (err) {
            console.log('insert err 10003' + err);
            notReady();
        }
        if (rows.length == 0)
            notReady();
        else {
            player2 = rows[0];
            if (player1 != null)
                allReady();
        }
    });
    function allReady() {
        var battleData = [];
        player1.skills = getSkill(connection, clientInfo.data.playerid1);
        player2.skills = getSkill(connection, clientInfo.data.playerid2);
        battleData = battle.start([player1, player2]);
        var protocolInfo = {
            protocol: clientInfo.protocol,
            data: {playerinfo1: player1, playerinfo2: player2, result: 1, msg: '请求战斗成功', battleData: battleData}
        };
        sendData(socket, protocolInfo);
        return;
    }

    function notReady() {
        var protocolInfo = {protocol: clientInfo.protocol, data: {result: 0, msg: '请求战斗失败'}};
        sendData(socket, protocolInfo);
        return;
    }
}

function pro10004(connection, socket, clientInfo) {
    var playerInfo = getPlayer(connection, clientInfo.data.playerid);
    if (playerInfo == null) {
        var protocolInfo = {protocol: clientInfo.protocol, data: {result: 2, msg: '获取玩家信息失败'}};
        sendData(socket, protocolInfo);
        return;
    }
    var VHealth = clientInfo.data.playerhealth - playerInfo.playerhealth;
    var VPower = clientInfo.data.playerpower - playerInfo.playerpower;
    var VIntelligence = clientInfo.data.playerintelligence - playerInfo.playerintelligence;
    var VGay = clientInfo.data.playergay - playerInfo.playergay;
    var VNc = clientInfo.data.playernc - playerInfo.playernc;
    var playerpoint;
    if (playerInfo.playerpoint < VHealth + VPower + VIntelligence + VGay + VNc) {
        var protocolInfo = {protocol: clientInfo.protocol, data: {result: 3, msg: '加点数大于玩家所拥有的点数，有作弊嫌疑'}};
        sendData(socket, protocolInfo);
        return;
    }
    playerpoint = playerInfo.playerpoint - VHealth - VPower - VIntelligence - VGay - VNc;
    var update = 'update player set playerhealth=' + clientInfo.data.playerhealth + ',playerpower=' + clientInfo.data.playerpower + ',playerintelligence=' + clientInfo.data.playerintelligence + ',playergay=' + clientInfo.data.playergay + ',playernc=' + clientInfo.data.playernc + ',playerpoint=' + playerpoint + ' where playerid="' + clientInfo.data.playerid + '"';
    connection.query(update, function (err, res) {
        if (err) {
            console.log('update err in 10004:' + err);
            var protocolInfo = {protocol: clientInfo.protocol, data: {result: 0, msg: '更新属性失败'}};
            sendData(socket, protocolInfo);
            return;
        }
        var protocolInfo = {protocol: clientInfo.protocol, data: {result: 1, msg: '更新属性成功'}};
        sendData(socket, protocolInfo);
    });
}

function pro10005(connection, socket, clientInfo) {
    var select = 'select * from backpack where id="' + playerId + '" limit 1';
    connection.query(select, function (err, rows) {
        if (err) {
            console.log('select err in pro10005:' + err);
            var protocolInfo = {protocol: clientInfo.protocol, data: {result: 0, msg: '获取背包列表失败'}};
            sendData(socket, protocolInfo);
            return;
        }
        var itemObj = [];
        if (rows[0].items) {
            var str = rows[0].items;
            var itemJson = str.replace(/\|/g, '\"');
            var itemObj = JSON.parse(itemJson);
        }
        var protocolInfo = {protocol: clientInfo.protocol, data: {result: 1, msg: '获取背包列表成功', items: itemObj}};
        sendData(socket, protocolInfo);
    });
}

function pro10006(connection, socket, clientInfo) {
    item.addItem(connection, clientInfo.protocol, clientInfo.data.id, clientInfo.data.num, socket);
}

function pro10007(connection, socket, clientInfo) {
    var select = 'select items from backpack where id="' + playerId + '"';
    var select2 = 'select skills from skill where id="' + playerId + '"';
    var itemLv = 1;
    connection.query(select, function (err, rows) {
        if (err) {
            console.log('select err in pro10007:' + err);
            var protocolInfo = {protocol: clientInfo.protocol, data: {result: 0, msg: '无法获取用户背包信息'}};
            sendData(socket, protocolInfo);
            return;
        }
        var str = rows[0].items.toString();
        var itemJson = str.replace(/\|/g, '\"');
        var itemsObj = JSON.parse(itemJson);
        for (var data in itemObj) {
            //用户拥有该技能
            if (itemsObj[data].id == clientInfo.data.id) {
                itemLv = itemsObj[data].lev;
                connection.query(select2, function (err, rows) {
                    if (err) {
                        console.log('select err in pro10007:' + err);
                        var protocolInfo = {protocol: clientInfo.protocol, data: {result: 0, msg: '无法获取用户技能信息'}};
                        sendData(socket, protocolInfo);
                        return;
                    }
                    //有技能数据返回。
                    if (rows[0].skills != null && rows[0].skills != '') {
                        var str2 = rows[0].skills.toString();
                        var skillsJson = str2.replace(/\|/g, '\"');
                        var skillsObj = JSON.parse(skillsJson);
                        //清除自身
                        for (var fuck in skillsObj) {
                            if (skillsObj[fuck].id == clientInfo.data.id) {
                                skillsObj.splice(fuck, 1);
                            }
                        }
                        for (var data2 in skillsObj) {
                            //该位置已有技能做替换动作
                            if (skillsObj[data2].position == clientInfo.data.position) {
                                skillsObj[data2].id = clientInfo.data.id;
                                skillsObj[data2].lev = itemLv;
                                skillsJson = JSON.stringify(skillsObj);
                                str2 = skillsJson.replace(/"/g, "|");
                                var update = 'update skill set skills="' + str2 + '" where id="' + playerId + '"';
                                connection.query(update, function (err, res) {
                                    if (err) {
                                        console.log('update err in pro10007:' + err);
                                        var protocolInfo = {
                                            protocol: clientInfo.protocol, data: {result: 0, msg: '无法更新用户技能信息'}
                                        };
                                        sendData(socket, protocolInfo);
                                        return;
                                    }
                                    var protocolInfo = {
                                        protocol: clientInfo.protocol,
                                        data: {result: 1, msg: '安装技能成功', skills: skillsObj}
                                    };
                                    sendData(socket, protocolInfo);
                                    return;
                                });
                            }
                        }
                        //该位置没有技能做插入动作
                        skillsObj.push({id: clientInfo.data.id, position: clientInfo.data.position, lev: itemLv});
                        skillsJson = JSON.stringify(skillsObj);
                        str2 = skillsJson.replace(/"/g, "|");
                        var update = 'update skill set skills="' + str2 + '" where id="' + playerId + '"';
                        connection.query(update, function (err, res) {
                            if (err) {
                                console.log('update err in pro10007:' + err);
                                var protocolInfo = {
                                    protocol: clientInfo.protocol, data: {result: 0, msg: '无法更新用户技能信息'}
                                };
                                sendData(socket, protocolInfo);
                                return;
                            }
                            var protocolInfo = {
                                protocol: clientInfo.protocol,
                                data: {result: 1, msg: '安装技能成功', skills: skillsObj}
                            };
                            sendData(socket, protocolInfo);
                            return;
                        });
                    }
                    //没有技能数据返回。
                    else {
                        var skillArr = [];
                        skillArr.push({id: clientInfo.data.id, position: clientInfo.data.position, lev: itemLv});
                        var json = JSON.stringify(skillArr);
                        var sss = json.replace(/"/g, "|");
                        var update = 'update skill set skills="' + sss + '" where id="' + playerId + '"';
                        connection.query(update, function (err, res) {
                            if (err) {
                                console.log('update err in pro10007:' + err);
                                var protocolInfo = {
                                    protocol: clientInfo.protocol,
                                    data: {result: 0, msg: '无法更新用户技能信息'}
                                };
                                sendData(socket, protocolInfo);
                                return;
                            }
                            var protocolInfo = {
                                protocol: clientInfo.protocol,
                                data: {result: 1, msg: '安装技能成功', skills: skillsObj}
                            };
                            sendData(socket, protocolInfo);
                            return;
                        });
                    }
                });
            }
        }
        //用户没有该技能
        var protocolInfo = {protocol: clientInfo.protocol, data: {result: 0, msg: '用户没有该技能'}};
        sendData(socket, protocolInfo);
        return;
    });
}
function pro10008(connection, socket, clientInfo) {
    var items = getBackpack(connection, playerId);
    if (items == null) {
        var protocolInfo = {protocol: clientInfo.protocol, data: {result: 0, msg: '用户没有该外观'}};
        sendData(socket, protocolInfo);
    }
    else {
        for (var data in items) {
            if (items[data].id == clientInfo.data.id) {
                var appearances = getAppearance(connection, playerId);
                if (appearances == null) {
                    var arr = [];
                    arr.push({id: clientInfo.data.id, type: clientInfo.data.type});
                    var json = JSON.stringify(arr);
                    var str = json.replace(/"/g, "|");
                    changeAppearance(connection, socket, playerId, arr, str, clientInfo.data.protocol);
                    return;
                }
                else {
                    for (var data2 in appearances) {
                        if (appearances[data2].type == clientInfo.data.type) {
                            appearances[data2].id = clientInfo.data.id;
                            var json = JSON.stringify(appearances);
                            var str = json.replace(/"/g, "|");
                            changeAppearance(connection, socket, playerId, appearances, str, clientInfo.data.protocol);
                            return;
                        }
                    }
                    appearances.push({id: clientInfo.data.id, type: clientInfo.data.type});
                    var json = JSON.stringify(appearances);
                    var str = json.replace(/"/g, "|");
                    changeAppearance(connection, socket, playerId, appearances, str, clientInfo.data.protocol);
                    return;
                }
            }
        }
        var protocolInfo = {protocol: clientInfo.protocol, data: {result: 0, msg: '用户没有该外观'}};
        sendData(socket, protocolInfo);
    }
}

function pro10009(connection, socket, clientInfo) {
    var appearance = getAppearance(connection, playerId);
    var protocolInfo;
    if (appearance == null)
        protocolInfo = {protocol: clientInfo.protocol, data: {result: 0, msg: '获取外观列表失败'}};
    else if (appearance == 0)
        protocolInfo = {protocol: clientInfo.protocol, data: {result: 1, msg: '获取外观列表成功', appearances: []}};
    else
        protocolInfo = {protocol: clientInfo.protocol, data: {result: 1, msg: '获取外观列表成功', appearances: appearance}};
    sendData(socket, protocolInfo);
}

function pro10010(connection, socket, clientInfo) {
    var skill = getSkill(connection, playerId);
    var protocolInfo;
    if (skill == null)
        protocolInfo = {protocol: clientInfo.protocol, data: {result: 0, msg: '获取技能列表失败'}};
    else if (skill == 0)
        protocolInfo = {protocol: clientInfo.protocol, data: {result: 1, msg: '获取技能列表成功', appearances: []}};
    else
        protocolInfo = {protocol: clientInfo.protocol, data: {result: 1, msg: '获取技能列表成功', skills: skill}};
    sendData(socket, protocolInfo);
}

function pro10011(connection, socket, clientInfo) {
    experience.changeExp(socket, clientInfo);
    experience.start((new Date).getTime());
    experience.end((new Date).getTime());
}

function pro10012(connection, socket, clientInfo) {
    if (clientInfo.data.type == 0)
        item.dropItem(connection, socket, clientInfo);
    else
        item.useItem(connection, socket, clientInfo);
}

function pro10013() {

}

function getAppearance(connection, playerId) {
    var select = 'select appearances from appearance where id="' + playerId + '"';
    connection.query(select, function (err, rows) {
        if (err) {
            console.log('select err in getAppearance:' + err);
            return null;
        }
        if (rows[0].appearances != null && rows[0].appearances != '') {
            var json = rows[0].appearances.replace(/\|/g, '\"');
            var obj = JSON.parse(json);
            return obj;
        }
        return 0;
    });
}

function changeAppearance(connection, socket, playerId, arrData, strData, protocol) {
    var update = 'update appearance set appearances="' + strData + '" where id="' + playerId + '"';
    connection.query(update, function (err, res) {
        if (err) {
            console.log('update err in changeAppearance:' + err);
            var protocolInfo = {protocol: protocol, data: {result: 0, msg: '装备外观失败'}};
            sendData(socket, protocolInfo);
        }
        else {
            var protocolInfo = {protocol: protocol, data: {result: 1, msg: '装备外观成功', appearances: arrData}};
            sendData(socket, protocolInfo);
        }
    });
}

function getPlayer(connection, id) {
    var select = 'select * from player where playerid="' + id + '" limit 1';
    connection.query(select, function (err, rows) {
        if (err) {
            console.log('select err in getPlayerInfo:' + err);
            return null;
        }
        return rows[0];
    });
}

function getBackpack(connection, playerId) {
    var select = 'select items from backpack where id="' + playerId + '"';
    connection.query(select, function (err, rows) {
        if (err) {
            console.log('select err in getBackpack:' + err);
            return null;
        }
        if (rows[0].items != null && rows[0].items != '') {
            var json = rows[0].items.replace(/\|/g, '\"');
            var obj = JSON.parse(json);
            return obj;
        }
        return [];
    });
}

exports.getBackpack = getBackpack;

function changeBackpack(connection, socket, playerId, arrData, strData, protocol) {
    var update = 'update backpack set items="' + strData + '" where id="' + playerId + '"';
    connection.query(update, function (err, res) {
        if (err) {
            console.log('update err in protocol/changeBackpack:' + err);
            var protocolInfo = {protocol: protocol, data: {result: 0, msg: '更新背包失败'}};
            sendData(socket, protocolInfo);
        }
        else {
            var protocolInfo = {protocol: protocol, data: {result: 1, msg: '更新背包成功', items: arrData}};
            sendData(socket, protocolInfo);
        }
    });
}

exports.changeBackpack = changeBackpack;

function sendData(socket, data) {
    var json = JSON.stringify(data);
    socket.send(json);
}

exports.sendData = sendData;

function getSkill(connection, playerId) {
    var select = 'select skills from skill where id="' + playerId + '"';
    connection.query(select, function (err, rows) {
        if (err) {
            console.log('select err in getSkill:' + err);
            return null;
        }
        if (rows[0].skills != null && rows[0].skills != '') {
            var json = rows[0].skills.replace(/\|/g, '\"');
            var obj = JSON.parse(json);
            return obj;
        }
        return 0;
    });
}